//输出最少需要的总步数（每匹马的步数相加），不存在则输出-1。
// 第一行输入m, n 表示m行n列的棋盘
// 后面m行, 表示棋盘的情况
// 这个题, 应该不难, 找到每个马, 遍历马的所有步数, 找到能踩的点位,统计点位对应的最小步数, 然后统计起来
// 遍历每一匹马, 看, 是否斗到了相同的点
const readline = require("readline");
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
let m, n;
let initArr = [];
rl.on("line", (line) => {
    if (m === undefined) {
        [m, n] = line.trim().split(/\s+/).map(Number)
    } else {
        initArr.push(line.trim().split(""))
        if (initArr.length === m) {
            console.log(getResult(m, n, initArr))

            // clear
            m = n = undefined
            initArr.length = 0
        }

    }

})

function getResult(m, n, initArr) {
    let ans = []
    // 遍历iniArr, 找到马
    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            if (initArr[i][j] !== ".") {
                let num = Number(initArr[i][j])
                ans.push(getSteps(i, j, num, m, n))
            }
        }
    }

    // 每个马给一个坐标数组 [{'x-y': step}], pq,  最后吧马的数据推进ans数组
    let result = Infinity
    outer: for (const [key, value] of Object.entries(ans.shift())) {
        let temp = value
        for (let i = 1; i < ans.length; i++) {
            let obj = ans[i]
            if (obj[key]) {
                temp += obj[key]
            } else {
                continue outer
            }
        }
        result = Math.min(result, temp)
    }

    if (result !== Infinity) {
        return result
    }
    return -1
}

function getSteps(x, y, num, m, n) {
    let result = {[`${x}-${y}`]: 0}
    let pq = [{[`${x}-${y}`]: 0}]
    let direction = [
        [1, 2],
        [1, -2],
        [2, 1],
        [2, -1],
        [-1, 2],
        [-1, -2],
        [-2, 1],
        [-2, -1]
    ]
    let index = 0
    while (pq.length && index < num) {
        for (let i = 0; i < pq.length; i++) {
            let [[str, step]] = Object.entries(pq.shift())
            const [x, y] = str.split("-").map(Number)
            for (const [addX, addY] of direction) {
                let newX = x + addX
                let newY = y + addY
                if (newX >= 0 && newY >= 0 && newX < m && newY < n) {
                    let newKey = `${newX}-${newY}`
                    let newStep = step + 1
                    if (!result[newKey]) {
                        result[newKey] = newStep
                        pq.push({[newKey]: newStep})
                    } else if (result[newKey] > newStep) {
                        result[newKey] = newStep
                        pq.push({[newKey]: newStep})
                    }
                }
            }
        }
        index++
    }
    return result
}
